package com.yzh.crypto;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;

public class Symmetric {
    public static void main(String[] args) throws NoSuchAlgorithmException {

        String content = "test中文";

        String value = SymmetricAlgorithm.AES.getValue();
        byte[] key = SecureUtil.generateKey(value).getEncoded();

        String encode = Base64.encode(key);
        System.out.println("密钥:" + encode);
        byte[] decode = Base64.decode(encode);
        System.out.println("密钥:" + ByteUtil.bytesToInt(decode));

        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        //加密
        byte[] encrypt = aes.encrypt(content);
        //解密
        byte[] decrypt = aes.decrypt(encrypt);
        //加密为16进制表示
        String encryptHex = aes.encryptHex(content);
        System.out.println(encryptHex);
        //解密为字符串
        String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
        System.out.println(decryptStr);

        AES aes1 = SecureUtil.aes(key);
        String jiami = aes1.encryptHex(content);
        System.out.println(jiami);

        AES aes2 = SecureUtil.aes(decode);
        String jeimi = aes2.decryptStr(jiami);
        System.out.println(jeimi);
    }

}
